<?php
/**
 * User: Administrator
 * Time: 2015/10/19 10:52
 */

//1、 如下代码是用表驱动法获取一个月的天数，但是没有考虑闰年情况，那么如何改造这个代码让它支持包含闰年的情况呢？

function getMonthDays($month) {
	$monthDays = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	$year      = date('Y');
	if (($year % 4 == 0) && ($year % 100 != 0) || ($year % 400 == 0)) $monthDays[1] = 29;
	return $monthDays[$month - 1];
}

echo getMonthDays(2) . PHP_EOL;

//2、 用preg_replace_callback函数对网页中的所有图片地址进行处理，gif改为png，高度和宽度互换

$str = '<img src="http://www.baidu.com/img/bd1.gif" width="278" height="127" />
<img src="http://www.baidu.com/img/logo2.gif" width="275" height="179" />';

$str = preg_replace_callback('/<img\s+src=".*\.(gif)"\s+width="(\d+)"\s+height="(\d+)"\s+\/>/', function ($matches) {
	$search  = array_merge(
		array($matches[1]),
		array('width="'.$matches[2].'"'),
		array('height="'.$matches[3].'"')
	);
	$replace = array_merge(
		array('png'),
		array('width="'.$matches[3].'"'),
		array('height="'.$matches[2].'"')
	);
	return str_replace($search, $replace, $matches[0]);
}, $str);

echo $str . PHP_EOL;


//用PHP实现关于UTF-8 的转换过程，已知Unicode码，得到这个Unicode码的UTF-8格式的汉字；反之，已经知道一个汉字的UTF-8字符串，提取出Unnicode码。

function unicodeToUtf8($unicode, $from_encoding = 10) {
	$unicode_map = array(
		'0xxxxxxx'                         => ['0000', '007F'],
		'110xxxxx10xxxxxx'                 => ['0080', '07FF'],
		'1110xxxx10xxxxxx10xxxxxx'         => ['0800', 'FFFF'],
		'11110xxx10xxxxxx10xxxxxx10xxxxxx' => ['010000', '10FFFF'],
	);
	$type        = $utf8 = '';
	foreach ($unicode_map as $k => $v) {
		$unicode_ten = base_convert($unicode, $from_encoding, 10);
		if ($unicode_ten > base_convert($v[0], 16, 10) && $unicode_ten < base_convert($v[1], 16, 10)) {
			$type = $k;
			break;
		}
	}
	if ($type) {
		$type    = strrev($type);
		$unicode = base_convert($unicode, $from_encoding, 2);
		$pos     = strlen($unicode) - 1;
		for ($i = 0; $i < strlen($type); $i++) {
			if ($type[$i] == 'x') {
				if (isset($unicode[$pos])) {
					$utf8 .= $unicode[$pos];
					$pos--;
				} else {
					$utf8 .= '0';
				}
			} else {
				$utf8 .= $type[$i];
			}
		}
		$utf8 = base_convert(strrev($utf8), 2, 16);
		return $utf8;
	}
	return false;
}

echo unicodeToUtf8(20320) . PHP_EOL;
//e4bda0

function utf8ToUnicode($utf8, $from_encoding = 16) {
	$utf8     = base_convert($utf8, $from_encoding, 2);
	$utf8_map = [
		'/^0(\d{7})$/',
		'/^110(\d{6})10(\d{6})$/',
		'/^1110(\d{4})10(\d{6})10(\d{6})$/',
		'/^11110(\d{3})10(\d{6})10(\d{6})10(\d{6})$/',
	];
	foreach ($utf8_map as $v) {
		if (preg_match($v, $utf8, $matched)) {
			unset($matched[0]);
			return base_convert(implode('', $matched), 2, 10);
		}
	}
	return false;
}

echo utf8ToUnicode('e4bda0') . PHP_EOL;
//20320

//用PHP的环视为数值添加金额所需的逗号：5345678986变为5,345,678,986.
//提示：
//我们需要找到一个位置，并将‘位置’替换为‘,’。
//这个位置需要符合下面几个条件。
//1）左边必须有数字
//2）右边的数字是3的倍数

$num = 4343434454445;

$num = preg_replace('/(?<=\d)(?=(\d{3})+$)/', ',', $num);
echo $num . PHP_EOL;
//4,343,434,454,445
